<?php

use yii\helpers\Html;
use yii\helpers\Url;
use dsj\components\grid\ResponsiveGridView;
use yii\widgets\ActiveForm;
use backend\modules\tool\models\Node;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
/* @var $model backend\modules\tool\models\Node */
\backend\modules\tool\Assets\SeachBundle::register($this);
\backend\modules\tool\Assets\VueBundle::register($this);
\backend\modules\tool\Assets\BaseBundle::register($this);
$source_config=\backend\modules\tool\helpers\ArrayHelper::array_parse_key_value(backend\modules\tool\models\SqlConfig::find()->select("id,source_name")->asArray()->all(),"id","source_name");
$SQL_URL=Url::to(["parse-sql"]);
$database_url=Url::to(["sql-config"]);
$this->title = '节点配置';
$this->params['breadcrumbs'][] = $this->title;
$log=Url::to(["log"]);
$anlyse_url=Url::to(["analyse"]);
$create_sql_url=\yii\helpers\Url::to(["create-sql"]);
$node=Url::to(['transform']);
$js=<<<js
new Vue({
el:"#app",
data:{
    page_data:{
        "data":[
            
        ],
        "total":0,
        "current_page":5,
        "total_page":1
    },
    command:[],
    current_page:1,
    showPages: 	5,
	totalPages: 20,
	id:null,
	layer_index:null,
	database:[],
	databaseMap:[],
	source:'',
	desc:'',
	mode:"strict",
	selected:true,
	prefix:"",
	tranformMap:[],
	run_num:"forever",
	run_time:"1*day",
	node_name:""//整库同步节点名称
},
watch: {
  current_page: {
    handler(newName, oldName) {
        if(newName==null){
            return;
        }
        if(newName==oldName){
            return;
        }
        if(this.id==null){
            return;
        }
        this.get_data(this.id,this.current_page)
    },
    // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
    immediate: true
  }
},
components: {
			'pagination': pagination
		},
methods:{
    transform(){
        layer.open({
              type: 1,
              shade: false,
              title: false, //不显示标题
              content: $('#transform'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
              area:["1200px","800px"],
              end:function (){
                  $('#transform').css("display","none");
              }
        });
    },
    before_tranform(){
      for(let i of this.databaseMap){
          if(!i.selected){
              continue;
          }
          this.tranformMap.push({
          sql_string:"select * from "+i['source'],
          desc_table:this.prefix+i.desc,
          run_fun:'',
          batch_size:1000,
          is_bind:1,
          way:'update',
          before_sql:'',
          source_config:this.source,
          desc_config:this.desc,
          node_name:i['source']+"到目标表:"+this.prefix+i.desc,
          node_desc:i['source']+"到目标表:"+this.prefix+i.desc,
          });
          let index=this.tranformMap.length-1;
          console.log(this.tranformMap);
          let self=this;
            axios.post('{$create_sql_url}',data={table:i['source'],source_config:this.source}).then(function(res) {
             self.tranformMap[index]['before_sql']=res['data']['data'];
             }).catch(function(err) {
               console.log(err)
             });
      }  
    },
    get_databse(){
        var self=this;
        axios.post('{$database_url}').then(function(res) {
            self.database=res.data.data;
        }).catch(function(err) {
          
        })
    },
    get_ananyse(){
        var self=this;
        axios.post('{$anlyse_url}&source='+this.source+"&desc="+this.desc+"&mode="+this.mode).then(function(res) {
            self.databaseMap=res.data.data;
            for(let index in self.databaseMap){
                if(self.databaseMap[index]['desc']==''){
                    self.databaseMap[index]['exits']=false;
                    self.databaseMap[index]['desc']=self.databaseMap[index]['source']
                }else {
                    self.databaseMap[index]['exits']=true;
                }
                self.databaseMap[index]['selected']=true;
            }
        }).catch(function(err) {
          
        })
    },
    code(text){
			        return "<pre><code>"+text+"</code></pre>";
			    },
    log(id){
        var self=this;
         axios.get('{$log}'+"&id="+id).then(function(res) {
           var data=res.data.data.split("=======================>");
           var log=[];
           for(var i of data){
               if(i.trim()!=""){
                   log.push(i)
               }
           }
           self.command=log;
           // if(self.layer_index!=null){
           //     layer.close(self.layer_index);
           // }
           setTimeout(function() {
             self.layer_index=layer.open({
              type: 1,
              shade: false,
              title: false, //不显示标题
              content: $('#log'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
              area:["1200px","800px"],
              end:function (){
                  $('#log').css("display","none");
              }
           });
           },1);
           
         }).catch(function(err) {
           
         })
    },
    
      get_form_title(){
      if(this.page_data['data'].length>0){
          return Object.keys(this.page_data['data'][0]);
      }
      return [];
    },
    remove(index){
      this.databaseMap[index].selected=!this.databaseMap[index].selected;
      this.\$forceUpdate();
    },
    startTranfrom(){
        for (let i of this.tranformMap){
            if(i.before_sql==''){
                layer.msg("未就绪请等待");
                return;
            }
        }
        if(this.node_name==''){
            layer.msg("请输入节点名称");
            return;
        }
        for (let index in this.tranformMap){
            this.tranformMap[index]['before_sql']=this.tranformMap[index]['before_sql'].replace(/EXISTS (.*?) \(/g,"EXISTS `"+this.tranformMap[index].desc_table+"` (");
        }
        axios.post("{$node}",Qs.stringify({name:this.node_name,data:this.tranformMap,run_time:this.run_time,run_num:this.run_num})).then(function (res){
            
        }).catch(function (err){
            
        });
    },
    select(){
        this.selected=!this.selected;
        for (let index in this.databaseMap){
            this.databaseMap[index].selected=this.selected;
        }
        let info=this.databaseMap;
        this.databaseMap=[];
        this.databaseMap=info;
        }
    ,
  get_data(id,page=1){
        this.id=id;
        var self=this;
      axios.get('{$SQL_URL}'+"&id="+id+"&page="+page)
  .then(function (response) {
      self.page_data=response.data;
      if(page!=1){
          return;
      }
      layer.open({
        type: 1,
        content: $('#show_data'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
          area: ['1200px', '600px'], //宽高
          end:function (){
            $('#show_data').css("display","none");
          }
        });
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  }
  }
,
created(){
    var self=this;
    setInterval(function() {
        if(self.current_page!=$("#current_page").text()){
            // alert($("#current_page").text());
      self.current_page=$("#current_page").text();
      }
    },10);
    this.get_databse();
},
})
js;
$this->registerJs($js);
//print_r(Node::GetTypeSelect("source_config"));die();
function get_config($filed){
    $data=\backend\modules\tool\helpers\ArrayHelper::array_parse_key_value(\backend\modules\tool\models\SqlConfig::find()
        ->select("source_name,id")
        ->andWhere(['in','id',array_values(Node::GetTypeSelect($filed))])
        ->asArray()
        ->all(),"id","source_name");
    $result=[""=>""];
    foreach ($data as $key=>$value){
        $result[$key]=$value;
    }
    return $result;
}
?>
<div class="Node-index" id="app">
    <div class="tranfrom-dev">
        <div id="transform" style="display: none;padding: 20px 20px;border: 1px solid lightgray">
            <div style="display: flex">
                <div class="source" style="width: 200px;">
                    <label for="sel1">数据源:</label>
                    <select class="form-control" id="source_list" v-model="source" name="source_config">
                        <option v-for="i in this.database" :value=i.id>{{i.source_name}}</option>
                    </select>
                </div>
                <div class="=desc" style="width: 200px;">
                    <label for="sel1">目标库:</label>
                    <select class="form-control" id="desc_list" v-model="desc" name="desc_config">
                        <option v-for="i in this.database" :value=i.id>{{i.source_name}}</option>
                    </select>
                </div>
                <div class="=desc" style="width: 200px;">
                    <label for="sel1">分析方式:</label>
                    <select class="form-control" id="desc_list" v-model="mode" name="desc_config">
                        <option value="strict">严格匹配</option>
                        <option value="like">模糊匹配</option>

                    </select>
                </div>
                <button style="height: 35px;margin-top: 23px;" type="button" class="btn btn-sm btn-primary" @click="get_ananyse">开始分析</button
            </div>
        </div>
        <div class="transfromPannel" style="border: 1px solid lightgray;padding: 15px 15px;box-shadow: lightgray">
            <table v-if="this.tranformMap.length==0" class="table">
                <thead>
                <tr>
                    <th>数据源表</th>
                    <th>转化</th>
                    <th>数据目标表</th>
                    <th>目标表状态</th>
                    <th v-if="this.selected">
                        <button @click="select" type="button" class="btn btn-sm btn-success">取消全选</button>
                    </th>
                    <th v-if="!this.selected">
                        <button @click="select" type="button" class="btn btn-sm btn-danger">全选</button>
                    </th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="i,index of this.databaseMap">
                    <td><input type="text" class="form-control" v-model="i.source" id="usr"></td>
                    <td>==></td>
                    <td v-if="i.exits"><input style="border: 1px solid #00c300" type="text" class="form-control" v-model="i.desc" id="usr"></td>
                    <td v-if="!i.exits"><input style="border: 1px solid #ff5e08" type="text" class="form-control" v-model="i.desc" id="usr"></td>
                    <td style="margin-top: 10px;" v-if="i.exits"><span class="label label-success">表已存在</span></td>
                    <td style="margin-top: 10px;" v-if="!i.exits"><span class="label label-primary">表不存在</span></td>
                    <td v-if="i.selected" style="margin-top: 10px;"><button @click="remove(index)" type="button" class="btn btn-sm btn-success">已经准备传输</button></td>
                    <td v-if="!i.selected" style="margin-top: 10px;"><button @click="remove(index)" type="button" class="btn btn-sm btn-danger">已被取消</button></td>
                </tr>
            </table>
            <div v-if="this.databaseMap.length>0">
                <div>
                    <lable>添加统一前缀</lable>
                    <input placeholder="默认为空" style="border: 1px solid #00c300" type="text" class="form-control" v-model="prefix" id="usr">
                </div>
                <button @click="before_tranform" style="margin-top: 30px" type="button" class="btn btn-sm btn-primary">执行传输前的必要准备</button>
            </div>
            <div v-if="this.tranformMap.length>0">
                <table class="table">
                    <thead>
                    <tr>
                        <th>数据源语句</th>
                        <th>数据目标表</th>
                        <th>预执行SQL语句</th>
                        <th>预执行程序</th>
                        <th>批量插入数量</th>
                        <th>使用参数绑定</th>
                        <th>主键冲突处理方式</th>
                        <th rowspan="2">状态</th>
                    </tr>
                    </thead>
                    <tbody>
                        <tr v-for="i,index of this.tranformMap">
                            <td><input type="text" class="form-control" v-model="i.sql_string" id="usr"></td>

                            <td><input type="text" class="form-control" v-model="i.desc_table" id="usr"></td>

                            <td><input type="text" class="form-control" v-model="i.before_sql" id="usr"></td>

                            <td><input type="text" class="form-control" v-model="i.run_fun" id="usr"></td>

                            <td><input type="text" class="form-control" v-model="i.batch_size" id="usr"></td>
                            <td>
                                <select v-model="i.is_bind" class="form-control"  id="sel1">
                                    <option value="1">使用参数绑定</option>
                                    <option value="0">普通模式</option>
                                </select>
                            </td>
                            <td>
                                <select v-model="i.way" class="form-control"  id="sel1">
                                    <option value="update">更新目标库</option>
                                    <option value="ignore">跳过此行</option>
                                </select>
                            </td>
                            <td>
                                <div v-if="i.before_sql==''">
                                    加载中...
                                </div>
                                <div v-else>
                                    完成
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div style="display: flex">
                    <div>
                        <input type="text" class="form-control" v-model="node_name" placeholder="请输入整库节点名称" id="usr">
                        <label>执行次数forever表示永久执行</label>
                        <input type="text" class="form-control" v-model="run_num" placeholder="执行次数" id="usr">
                        <label>执行间隔</label>
                        <input type="text" class="form-control" v-model="run_time" placeholder="执行间隔" id="usr">
                        <button type="button" @click="startTranfrom" class="btn btn-sm btn-success">开始同步</button>
                    </div>

                </div>
            </div>
        </div>
    </div>
    <div style="max-height:800px;overflow-y: scroll;left: 0;width: 100%;display: none;padding: 20px;" id="log">
        <div class="code" v-for="i in command" style="">
            <pre v-html="code(i)"></pre>
        </div>
    </div>
    <div id="show_data" style="display: none">
        <table class="table">
            <caption>数据源</caption>
            <thead>
            <tr>
                <th  v-for="i in get_form_title()">{{i}}</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="i in page_data['data']">
                <td v-for="name of i">{{name}}</td>
            </tr>
            </tbody>
        </table>
        <pagination :show-pages="showPages" :curPage="5" :total-pages="page_data['total_page']" ref="pagination"></pagination>
        <p>{{this.$refs.curPage}}</p>
    </div>
    <?= Html::button('新增节点', ['class' => 'btn btn-success data-create','url' => Url::to(['create'])]) ?>
    <button type="button" class="btn btn-info" @click="transform">整库同步</button>
    <?php $back_url=Url::to(['/tool/data-base-back']) ?>
    <button type="button" class="btn btn-primary" onclick="window.location.href='<?=$back_url?>'">整库备份</button>
<!--    --><?//= Html::button('数据源', ['class' => 'btn btn-primary data-create','url' => Url::to(['/tool/sql-config'])]) ?>
    <?php $sql_url=Url::to(['/tool/sql-config']) ?>
    <button type="button" class="btn btn-primary" onclick="window.location.href='<?=$sql_url?>'">数据源配置</button>

    <div style="display: flex;width: 400px;position: relative;margin: 0 auto">
        <button type="button" class="btn btn-sm btn-info" @click="log('main')">主进程日志</button>
        <?php if(\backend\modules\tool\DataSource\Log\PidRecord::SingleTon("main")->IsRun()):?>
            <button type="button" class="btn btn-sm btn-success">主进程正在运行</button>
        <?php else:?>
            <button type="button" class="btn btn-sm btn-warning">主进程已停止运行</button>
        <?php endif;?>
    </div>

<?php $form = ActiveForm::begin(['method'=>'get']); ?>
<?= $form->field($model, 'node_name')->textInput(['maxlength' => true]); ?>
    <?= $form->field($model, 'source_config')->dropDownList(get_config("source_config")) ?>
    <?= $form->field($model, 'desc_config')->dropDownList(get_config("desc_config"))?>
    <?= $form->field($model, 'desc_table')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'sql_string')->textInput(['maxlength' => true])?>
<!--    --><?//= \backend\modules\tool\helpers\widgets\SwitcButton::widget([]) ?>
    <?= $form->field($model, 'pid')->dropDownList(Node::GetTypeSelect("pid")) ?>
<!--    --><?//= $form->field($model, 'source_conifg')->dropDownList(\backend\modules\tool\models\SqlConfig::find()->select()) ?>
<?= Html::submitButton('搜索', ['class' => 'btn btn-primary btn-search']) ?>
    <button type="button" class="btn btn-default reload">重置</button>
<?php ActiveForm::end(); ?>
    <?= \yii\grid\GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'node_name',
            [
                'attribute' => 'sql_string',
                'label' => 'SQL源语句',
                'value' => function($model)use($source_config){
                    return mb_substr($model->sql_string,0,30)."...";
                }
            ],
            [
                'attribute' => 'source_config',
                'label' => '数据来源',
                'value' => function($model)use($source_config){
                    return $source_config[$model->source_config];
                }
            ],
            [
                'attribute' => 'desc_config',
                'label' => '数据去向',
                'value' => function($model)use($source_config){
                    return $source_config[$model->desc_config];
                }
            ],
//            'fileds_mapping',
//            'before_sql',
//            'node_desc',

            ['class' => \backend\modules\tool\helpers\ResponsiveActionColumn::class,
             'template'=> '{parse-sql} {add-task} {create} {update} {view} {delete} {switch} {log}',
                    'buttons' => [
                        'parse-sql' => function ($url, $model, $key) {
                            return "<button type='button' @click='get_data({$model->id})' class='btn btn-sm btn-success'>查看数据</button>";
                        },
                        'add-task'=>function($url, $model, $key){
                            return sprintf("<button type=\"button\" class=\"btn btn-primary btn-sm data-view\" title=\"查看\" aria-label=\"查看\" data-pjax=\"0\" url='%s'>节点运行配置</button>",Url::to(["add-task"])."&task_id=".$model->id);
                        },
                        'switch'=>function($url, $model, $key){
                            if(\backend\modules\tool\DataSource\Log\PidRecord::SingleTon($model->id)->IsRun()){
                                return "<button type=\"button\" class=\"btn btn-sm btn-success\">运行中</button>";
                            }else{
                                return "<button type=\"button\" class=\"btn btn-sm btn-secondary\">未运行</button>";
                            }
                        },
                        "view"=>function($url, $model, $key){
                               return "";
                        },
                        "log"=>function($url, $model, $key){
                            return "<button type=\"button\" class=\"btn btn-sm btn-info\" @click=\"log($model->id)\">日志</button>";
                        }
                    ]],]
    ]); ?>
</div>
